import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useMemberStore = defineStore(
    'member',
    () => {
        // 定义用户信息
        const userInfo = ref({})
        const token = ref('')
        const userType = ref(1)
        const companyList = ref([])
        const userCompanyName = ref()

        // 存储用户信息
        const setUserInfo = (val) => {
            userInfo.value = val
        }
        // 清除用户信息
        const clearUserInfo = () => {
            userInfo.value = undefined
            token.value = ''
            userType.value = 1
            companyList.value = []
            userCompanyName.value = ''
        }
        // 存储 token
        const setToken = (val) => {
            token.value = val
        }
        // 清除 token
        const clearToken = (val) => {
            token.value = undefined
        }
        // 切换用户角色
        const editUserType = (val) => {
            userType.value = val
        }
        // 存储公司列表
        const setCompanyList = (list) => {
            companyList.value = list
        }
        // 存储公司名称
        const setCompanyName = (name) => {
            userCompanyName.value = name
        }

        // 把数据和方法 return 出去
        return {
            userInfo,
            token,
            userType,
            companyList,
            userCompanyName,
            setToken,
            clearToken,
            setUserInfo,
            editUserType,
            setCompanyName,
            clearUserInfo,
            setCompanyList,
        }
    },

    // 用户信息持久化处理
    {
        persist: {
            storage: {
                getItem(key) {
                    return uni.getStorageSync(key)
                },
                setItem(key, value) {
                    uni.setStorageSync(key, value)
                },
            },
        },
    },
)
